import requests
import zmail
import time
import os
from dotenv import load_dotenv

load_dotenv(override=True)

url = "https://v2.alapi.cn/api/zaobao"
emailKey = os.getenv('emailKey')
myCodeNexusPath = os.getenv('myCodeNexusPath')

server = zmail.server('chatgptemailbot@163.com', emailKey)
payload = "token=7XzYphnEf5YENgaq"
headers = {'Content-Type': "application/x-www-form-urlencoded"}
users=["1915141975@qq.com","2499882140@qq.com"]

with open(myCodeNexusPath+'/py/tools/hadSent.log', "w+", encoding='utf-8') as f:
    days = f.read()

hour=int(time.strftime('%H', time.localtime()))
today=time.strftime('%Y-%m-%d', time.localtime())
if(hour > 9 and today not in days): 

    response = requests.request("POST", url, data=payload, headers=headers)
    tmp = response.json()
    content_text =""
    for i in tmp['data']['news']:
        content_text = content_text+i[i.find("、")+1:]+'\n\n'
    
    subject="每日60秒新闻 "+tmp['data']['date']

    for user in users:
        print("have sent email to " + user)
        server.send_mail(user, {'subject': subject,'content_text': content_text})
    
    with open(myCodeNexusPath+'/py/tools/hadSent.log', "a+", encoding='utf-8') as f:
        f.write(time.strftime(today)+'\n')
